﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;

namespace CZ.PAEZ.SaleManager.FormPlugIns
{
    [Description("销售订单表单")]
    [HotUpdate]
    public class SaleOrder : AbstractBillPlugIn
    {
        public override void AfterBindData(EventArgs e)
        {
            base.AfterBindData(e);
            string FSaleOrgId = (this.Model.GetValue("FSaleOrgId") as DynamicObject)?["Id"].ToString();
            if (!FSaleOrgId.Equals("100010"))
            {
                this.View.GetControl("F_PAEZ_ReferencePrice").Visible = false;
            }
        }

        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            string key = e.Field.Key.ToUpperInvariant();
            switch (key)
            {
                case "FMATERIALID": // FMaterialId 物料
                    Act_DC_GetReferencePrice(e.Row);
                    break;
                case "FLOT": // FLot 批号
                    Act_DC_GetReferencePrice(e.Row);
                    break;
                case "FDISCOUNTRATE": //FDiscountRate 折扣率%
                    this.Model.SetValue("F_PAEZ_Discount", 100 - Convert.ToDecimal(e.NewValue), e.Row);
                    break;
            }
        }

        public override void BeforeDoOperation(BeforeDoOperationEventArgs e)
        {
            base.BeforeDoOperation(e);
            switch (e.Operation.FormOperation.Operation.ToUpperInvariant())
            {
                case "SAVE":
                    Act_BDO_IsLowerNormalPrice(e);
                    break;
            }
        }

        /// <summary>
        /// 判断价格是否有低于物料对于某个供应商的原价
        /// </summary>
        private void Act_BDO_IsLowerNormalPrice(BeforeDoOperationEventArgs e)
        {
            int count = this.Model.GetEntryRowCount("FSaleOrderEntry");
            int isLowPrice = 0;
            for (int i = 0; i < count; i++)
            {
                string FMaterialId = (this.Model.GetValue("FMaterialId", i) as DynamicObject)?["Id"].ToString();
                if (FMaterialId.IsNullOrEmptyOrWhiteSpace()) continue;
                decimal FTaxNetPrice = Convert.ToDecimal(this.Model.GetValue("FTaxNetPrice", i));
                decimal FQty = Convert.ToDecimal(this.Model.GetValue("FQty", i));
                string sql = string.Format(@"/*dialect*/
declare @price decimal(23, 6)=0
select @price=ple.FPrice from T_SAL_PRICELISTENTRY ple
where ple.FMaterialId={0}
declare @discount_rate decimal(23, 6)=0
select @discount_rate=FDiscountRate from T_SAL_DISCOUNTLISTENTRY dle
where dle.FMaterialId={0}
select @price FPrice, @discount_rate FDiscountRate
", FMaterialId);
                var price = DBUtils.ExecuteDynamicObject(Context, sql).FirstOrDefault();
                if(price == null)
                {
                    this.Model.SetValue("F_PAEZ_BeforePrice", FTaxNetPrice, i);
                }
                else
                {
                    decimal discountRate = Convert.ToDecimal(price["FDiscountRate"]);
                    decimal srcPrice = Math.Round(Convert.ToDecimal(price["FPrice"]) * (100 - discountRate) / 100, 2);
                    this.Model.SetValue("F_PAEZ_SysDiscountRate", discountRate, i);
                    this.Model.SetValue("F_PAEZ_SysDiscount", 100 - discountRate, i);
                    this.Model.SetValue("F_PAEZ_BeforePrice", srcPrice, i);
                    this.Model.SetValue("F_PAEZ_AmtDiff", (srcPrice - FTaxNetPrice) * FQty, i);
                    if(srcPrice - FTaxNetPrice > 0.05M)
                    {
                        // 订单行价格小于该物料对于客户价格(=源价格*(100-折扣率)/100)时，需要审批
                        isLowPrice = 1;
                    }
                }
                decimal discount = Convert.ToDecimal(this.Model.GetValue("FDiscountRate", i));
                this.Model.SetValue("F_PAEZ_Discount", 100 - discount, i);
            }
            this.Model.SetValue("F_PAEZ_NeedCheck", isLowPrice);
            if (isLowPrice == 1)
            {
                Act_CheckLowType(e);
            }
        }

        /// <summary>
        /// 判定低价类型是否录入
        /// </summary>
        /// <param name="e"></param>
        private void Act_CheckLowType(BeforeDoOperationEventArgs e)
        {
            string FSaleOrgId = (this.Model.GetValue("FSaleOrgId") as DynamicObject)?["Id"].ToString() ?? "0";
            // 不为上手时跳过
            if (!FSaleOrgId.Equals("100008")) return;
            string billtype = (this.Model.GetValue("FBillTypeID") as DynamicObject)?["Id"].ToString() ?? "";
            // 不为标准销售订单不进行判断
            if (!billtype.Equals("eacb50844fc84a10b03d7b841f3a6278")) return;

            string FUseRebate = this.Model.GetValue("F_PAEZ_UseRebate")?.ToString();
            string FNominalDj = this.Model.GetValue("F_PAEZ_NominalDj")?.ToString();
            string FSalWmDj = this.Model.GetValue("F_PAEZ_SalWmDj")?.ToString();
            string FSalZbDj = this.Model.GetValue("F_PAEZ_SalZbDj")?.ToString();

            int cnt = 0;
            // 使用返利
            if (FUseRebate.Equals("True")) 
            {
                cnt++;
                var entity = this.Model.DataObject["SaleOrderEntry"] as DynamicObjectCollection;
                int num = entity.Where(x => Convert.ToDecimal(x["F_PAEZ_AmtDiff"]) < 0).Count();
                if (num > 0)
                {
                    e.Cancel = true;
                    this.View.ShowErrMessage("单据体中存在差额为负数的情况，不适用于使用返利类型，请选择其他低价类型!");
                    return;
                }
            }
            // 正常低价
            if (FNominalDj.Equals("True")) 
            {
                cnt++;
                string FCustId = (this.Model.GetValue("FCustId") as DynamicObject)?["Id"].ToString() ?? "0";
                string sql = $"select F_PAEZ_ZCDJ from T_BD_CUSTOMER where FCUSTID={FCustId} and F_PAEZ_ZCDJ=1";
                var item = DBUtils.ExecuteDynamicObject(Context, sql).FirstOrDefault();
                if (item == null) 
                {
                    e.Cancel = true;
                    this.View.ShowErrMessage("客户不适用于正常低价类型，请选择其他低价类型!");
                    return;
                }
            }
            if (FSalWmDj.Equals("True")) cnt++;
            if (FSalZbDj.Equals("True")) cnt++;
            if (cnt == 0)
            {
                this.View.ShowErrMessage("必须选择一种低价订单类型!");
                e.Cancel = true;
            }
            else if (cnt > 1)
            {
                this.View.ShowErrMessage("仅能选择一种低价订单类型!");
                e.Cancel = true;
            }
        }


        /// <summary>
        /// 获取参考价格，通过订单的物料和批号获取采购入库单的价格，如果价格为0则获取其成本
        /// </summary>
        /// <param name="row"></param>
        private void Act_DC_GetReferencePrice(int row)
        {
            string FSaleOrgId = (this.Model.GetValue("FSaleOrgId") as DynamicObject)?["Id"].ToString();
            if (!FSaleOrgId.Equals("100010"))
            {
                return;
            }
            string FMaterialId = (this.Model.GetValue("FMaterialId", row) as DynamicObject)?["Id"].ToString();
            string FLot = this.Model.GetValue("FLot", row)?.ToString();
            if (FMaterialId.IsNullOrEmptyOrWhiteSpace() || FLot.IsNullOrEmptyOrWhiteSpace())
            {
                return;
            }

            string sql = $"select FPrice,FCostPrice from T_STK_INSTOCKENTRY ie " +
                "inner join T_STK_INSTOCKENTRY_F ief ON ief.FEntryId=ie.FEntryId " +
                $"where FMaterialId={FMaterialId} and FLOT_TEXT='{FLot}'";
            var items = DBUtils.ExecuteDynamicObject(Context, sql);
            if(items.Count <= 0)
            {
                return;
            }
            decimal FPrice = Convert.ToDecimal(items[0]["FPrice"]);
            decimal FCostPrice = Convert.ToDecimal(items[0]["FCostPrice"]);
            decimal p = FPrice > 0 ? FPrice : FCostPrice;
            this.Model.SetValue("F_PAEZ_ReferencePrice", p, row);
        }
    }
}
